package com.aliyun.messagemgt.typehandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.messagemgt.common.dto.send.MsgBody;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IDEA
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/4/4
 * @time:9:21
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ContentJsonTypeHandler extends BaseTypeHandler<List<MsgBody>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<MsgBody> msgBodies, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(msgBodies));
    }

    @Override
    public List<MsgBody> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JSONArray.parseArray(resultSet.getString(s), MsgBody.class);
    }

    @Override
    public List<MsgBody> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return JSONArray.parseArray(resultSet.getString(i), MsgBody.class);
    }

    @Override
    public List<MsgBody> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return JSONArray.parseArray(callableStatement.getString(i), MsgBody.class);
    }
}
